import {findFightRecords} from 'api/combat';
import {useEffect, useState, useRef} from 'react';
import {Text, View, Image, Pressable} from 'react-native';
import {Icon} from 'react-native-paper';
import Timeline from 'react-native-timeline-flatlist';
import {ActivityIndicator} from 'react-native-paper';
// import {PESDK} from 'react-native-photoeditorsdk';
import RNFS from 'react-native-fs';
import useDimensions from 'hooks/useDimensions';
type IndexType = {
  index: number;
};
export default ({
  route,
  patrolCommandId,
}: Partial<RootStackScreenProps<'fightRecords'>> & {
  patrolCommandId: number | string;
  needFilter?: boolean;
}) => {
  const [TimelineList, setTimelineList] = useState<
    (Api.resBody['作战指挥记录'] & IndexType)[]
  >([]);
  const [inactive, setInactive] = useState(0);
  const [loading, setLoading] = useState(false);
  const inactiveRef = useRef(inactive);
  const hp = useDimensions();
  const renderDetail = (rowData: Api.resBody['作战指挥记录'] & IndexType) => {
    return (
      <View style={{flex: 1}}>
        <Text
          style={{
            fontSize: 20 * hp,
            fontWeight: '500',
            color:
              rowData.index === inactiveRef.current
                ? '#0A59F7'
                : 'rgba(0, 0, 0, 0.90)',
          }}>
          {rowData.creatorName}
        </Text>
        <View style={{flexDirection: 'row', alignItems: 'center'}}>
          <Icon size={12 * hp} source={'clock-time-nine-outline'} />
          <Text
            style={{
              fontSize: 16 * hp,
              color: 'rgba(0, 0, 0, 0.60)',
              marginLeft: 1,
            }}>
            {rowData.createDate}
          </Text>
        </View>
        {rowData.designUrl && (
          <Image
            style={{
              width: 300 * hp,
              height: 200 * hp,
              borderRadius: 16 * hp,
              marginTop: 12 * hp,
            }}
            source={{uri: rowData.designUrl}}
          />
        )}
      </View>
    );
  };
  // const hasFileExists = (imageUrl: string) => {
  //   const regex = /\/([^\/]+\.png)$/;
  //   const match = imageUrl.match(regex);
  //   const filename = match?.[1] ?? '';
  //   setLoading(true);
  //   RNFS.exists(RNFS.DocumentDirectoryPath + `/${filename ?? ''}`).then(
  //     async result => {
  //       if (result) {
  //         setLoading(false);
  //         await PESDK.openEditor(
  //           RNFS.DocumentDirectoryPath + `/${filename ?? ''}`,
  //         );
  //       } else {
  //         saveImageToLocal(imageUrl, filename);
  //       }
  //     },
  //   );
  //   return filename;
  // };
  // const saveImageToLocal = async (imageUrl: string, filename: string) => {
  //   try {
  //     RNFS.downloadFile({
  //       fromUrl: imageUrl,
  //       toFile: RNFS.DocumentDirectoryPath + `/${filename ?? ''}`,
  //     })
  //       .promise.then(async () => {
  //         setLoading(false);
  //         await PESDK.openEditor(
  //           RNFS.DocumentDirectoryPath + `/${filename ?? ''}`,
  //         );
  //       })
  //       .catch(err => {
  //         console.log(err);
  //       });
  //   } catch (error) {
  //     setLoading(false);
  //     console.error('Error saving image:', error);
  //   }
  // };
  useEffect(() => {
    findFightRecords({
      patrolCommandId: route?.params?.id ? route.params.id : patrolCommandId,
    }).then(res => {
      const List = res.reverse().map((item, index) => {
        return {index, ...item};
      });
      setTimelineList(List);
    });
  }, []);
  return (
    <View style={{flex: 1, flexDirection: 'row', padding: 12}}>
      <ActivityIndicator
        animating={loading}
        style={{
          position: 'absolute',
          left: '50%',
          top: '50%',
          zIndex: 100,
        }}
        size={'large'}
      />
      <Timeline
        data={TimelineList}
        showTime={false}
        renderDetail={renderDetail}
        style={{
          flex: 1,
          backgroundColor: '#fff',
          borderRadius: 16,
          paddingTop: 16 * hp,
        }}
        circleColor="rgba(10, 89, 247, 0.10)"
        lineColor="rgba(0, 0, 0, 0.10)"
        isUsingFlatlist
        innerCircle={'dot'}
        dotColor="rgba(10, 89, 247, 1)"
        onEventPress={e => {
          setInactive((e as unknown as IndexType).index);
          inactiveRef.current = (e as unknown as IndexType).index;
        }}
      />
      <View
        style={{
          flex: 2.2,
          borderRadius: 16,
          backgroundColor: '#fff',
          marginLeft: 16 * hp,
          justifyContent: 'center',
          alignItems: 'center',
        }}>
        {TimelineList[inactive] && (
          <>
            <View
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'center',
                width: '94%',
                marginBottom: 16 * hp,
              }}>
              <Text
                style={{
                  fontSize: 26 * hp,
                  fontWeight: '500',
                  color: 'rgba(0, 0, 0, 0.90)',
                }}>
                {TimelineList[inactive].creatorName}
              </Text>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                }}>
                <Icon size={16 * hp} source={'clock-time-nine-outline'} />
                <Text style={{marginLeft: 2}}>
                  {TimelineList[inactive].createDate}
                </Text>
              </View>
            </View>
            <Pressable
              style={{
                width: '94%',
                height: '85%',
              }}
              // onLongPress={() => {
              // hasFileExists(TimelineList[inactive].designUrl as string);
              // saveImageToLocal(TimelineList[inactive].imageUrl, navigation);
              //}}
            >
              <Image
                style={{
                  width: '100%',
                  height: '100%',
                  borderRadius: 12,
                }}
                source={{uri: TimelineList[inactive].designUrl}}
              />
            </Pressable>
          </>
        )}
      </View>
    </View>
  );
};
